package liuch.basic;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author 17101651 on 2018/3/5.
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
class WaitNotify implements Runnable {
    private int number;
    public byte res[];
    public int count = 5;

    public WaitNotify(int number, byte a[]) {
        this.number = number;
        res = a;
    }

    @Override
    public void run() {
        synchronized (res) {
            while (true) {
                try {
                    res.notify();//唤醒等待res资源的线程，把锁交给其他获得该锁线程（该同步锁执行完毕自动释放锁）
                    System.out.println(" " + number);
                    Thread.sleep(1000);
                    res.wait();//释放CPU控制权，释放res的锁，本线程阻塞，等待被唤醒。
                    System.out.println("------线程" + Thread.currentThread().getName() + "获得其他线程notify让出的锁，wait()后的代码继续运行：" + number);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }//end of while
        }//synchronized

    }

    public static void main(String args[]) {
        final byte a[] = {0};//以该对象为共享资源
        Thread thread1 = new Thread(new WaitNotify((1), a), "1");
        Thread thread2 = new Thread(new WaitNotify((2), a), "2");
        thread1.start();
        thread2.start();
    }
}
